package com.nowcoder.community.config;

import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter implements CommunityConstant{

    @Override
    public void configure(WebSecurity web) throws Exception {
        //所有的静态资源都不必过滤，可直接访问
        web.ignoring().antMatchers("/resources/**");
    }

    //授权设置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //设置要授权的路径
        http.authorizeRequests().antMatchers(
//                "/user/setting",
//                "/user/upload",
//                "/discusspost/add",
//                "/comment/add/**",
//                "/letter/detail/**",
//                "/notice/detail/**",
//                "/like",
//                "/follow",
//                "/unFollow"
        ).hasAnyAuthority(//上述的路径在下面三个权限下都可以访问
                AUTHORITY_USER,//普通用户
                AUTHORITY_ADMIN,//管理员
                AUTHORITY_MODERATOR//版主
        ).antMatchers(
                "/discusspost/top",
                "/discusspost/wonderful"
        ).hasAnyAuthority(//上述的路径只有版主才能访问
                AUTHORITY_MODERATOR//版主
        ).antMatchers(
                "/discusspost/delete"
//                "/data/**",
//                "/actuator/**"
        ).hasAnyAuthority(//上述的路径只有管理员才能访问
                AUTHORITY_ADMIN//管理员
        ).anyRequest().permitAll()//除了上述的路径外，其他的路径在任意权限下都可以访问
                .and().csrf().disable();//禁用csrf功能


        http.exceptionHandling()
                //authenticationEntryPoint：设置没有登录时的处理方式
                .authenticationEntryPoint(new AuthenticationEntryPoint() {
                    @Override
                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
                        //获取请求头
                        String requestHeader = request.getHeader("x-request-with");
                        //判断请求头是否是异步请求
                        if ("XMLHttpRequest".equals(requestHeader)){
                            response.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer = response.getWriter();
                            writer.write(CommunityUtil.getJSONString(403, "你还未登录！"));
                        }else {//如果是同步请求
                            //重定向到登录页面
                            response.sendRedirect(request.getContextPath() + "/login");
                        }
                    }
                })
                //设置权限不够时的处理方式
                .accessDeniedHandler(new AccessDeniedHandler() {
                    @Override
                    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
                        //获取请求头
                        String requestHeader = request.getHeader("x-request-with");
                        if ("XMLHttpRequest".equals(requestHeader)){
                            response.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer = response.getWriter();
                            writer.write(CommunityUtil.getJSONString(403, "你没有访问此功能的权限！"));
                        }else {
                            //重定向到登录页面
                            response.sendRedirect(request.getContextPath() + "/denied");
                        }
                    }
                });

        //security底层会默认会拦截/logout请求，进行退出处理
        //覆盖security底层默认的逻辑，才能执行我们自定义的退出登录的代码
        http.logout().logoutUrl("/securityLogout");
    }
}
